/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package edu.uoc.tdp.pac4.servidor;

import edu.uoc.tdp.pac4.comun.GestorAdministrativaInterface;
import edu.uoc.tdp.pac4.comun.GestorConexionInterface;
import edu.uoc.tdp.pac4.comun.GestorEstadisticasInterface;
import edu.uoc.tdp.pac4.comun.GestorReparacionesInterface;
import edu.uoc.tdp.pac4.comun.Utils;
import edu.uoc.tdp.pac4.i18n.TDSLanguageUtils;
import java.awt.Dimension;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.rmi.NoSuchObjectException;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.rmi.server.UnicastRemoteObject;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import javax.swing.JButton;
import javax.swing.JInternalFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;

/**
 *
 * @author pguerreroj
 * 
 * EJEMPLO DE SERVIDOR RMI PARA ACEPTAR LAS PETICIONES DESDE EL CLIENTE 
 * 
 * 
 */
public class EjemploServidor extends JInternalFrame{
    
    private static final long serialVersionUID = 1L;
    private static final int PORT = 1099;
    private final String URL = "localhost";
    private final String JNDI_NAME_Conexion = "Serv_Conexion";
    private final String JNDI_NAME_Reparaciones = "Serv_Reparaciones";    
    private final String JNDI_NAME_Administrativa = "Serv_Administrativa";
    private final String JNDI_NAME_Estadisticas = "Serv_Estadisticas";     
    private Registry registry;        
    GestorConexionInterface gestorConexion=null;
    GestorEstadisticasInterface gestorEstadisticas=null;
    GestorAdministrativaInterface gestorAdministrativa=null;
    GestorReparacionesInterface gestorReparaciones=null;
    
    
    private JButton jButton1;
    private JButton jButton2;
    private JLabel jLabel2;
    private JPanel jPanel = null;  
    private boolean activo=false;   
    private static JTextArea text;
    
    
    public EjemploServidor() {
        seleccionDeIdioma();
        iniciarPantalla();
        setServidorActivo(false);
    }
    
    private void seleccionDeIdioma() {
        Locale localLocale = new Locale("es", "ES");
        TDSLanguageUtils.setDefaultLanguage("i18n/messages");
    }
    
    private void iniciarPantalla() {
        setTitle(TDSLanguageUtils.getMessage("Aplication.title"));
        activo=false;
        this.jLabel2 = new JLabel();
        this.jButton2 = new JButton();
        this.jButton1 = new JButton();
        setDefaultCloseOperation(3);
        setPreferredSize(new Dimension(472, 406));
        setContentPane(getJPanel());
        setSize(new Dimension(472, 406));

        this.jButton2.setText(TDSLanguageUtils.getMessage("RMI.stop"));
        this.jButton2.setBounds(new Rectangle(227, 34, 225, 26));
        this.jButton2.addMouseListener(new MouseAdapter() {
            public void mouseReleased(MouseEvent paramAnonymousMouseEvent) {
                EjemploServidor.this.jButton2MouseReleased(paramAnonymousMouseEvent);
            }
        });
        this.jButton1.setText(TDSLanguageUtils.getMessage("RMI.start"));
        this.jButton1.setBounds(new Rectangle(11, 34, 211, 26));
        this.jButton1.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent paramAnonymousActionEvent) {
                EjemploServidor.this.jButton1ActionPerformed(paramAnonymousActionEvent);
            }
        });
        JScrollPane jScrollPane1 = new JScrollPane();
        jScrollPane1.setBounds(new Rectangle(10, 80, 450, 350));
        this.text = new JTextArea();
        this.text.setBounds(new Rectangle(10, 80, 450, 350));
        jScrollPane1.setViewportView(this.text);
        add(jScrollPane1);

        setResizable(true);
        pack();
    }
    
    private void jButton2MouseReleased(MouseEvent paramMouseEvent) {
        StopRMIServidor();
    }

    private void jButton1ActionPerformed(ActionEvent paramActionEvent) {
         StartRMIServidor();
    }
    
    private JPanel getJPanel() {
        if (this.jPanel == null) {
            this.jLabel2 = new JLabel();
            this.jLabel2.setBounds(new Rectangle(11, 5, 442, 27));
            this.jPanel = new JPanel();
            this.jPanel.setLayout(null);
            this.jPanel.add(this.jButton2, null);
            this.jPanel.add(this.jButton1, null);
            this.jPanel.add(this.jLabel2, null);	
        }
        return this.jPanel;
    }
    
    public void StartRMIServidor() {
        try {
            GestorInterfaceImpl localRemotoImpl = new GestorInterfaceImpl();
            GestorConexionImpl  localConexionImpl = new GestorConexionImpl();
            GestorAdministrativaImpl localAdministrativaImpl = new GestorAdministrativaImpl();
            GestorReparacionesImpl localReparacionesImpl = new GestorReparacionesImpl();
            
            registry = LocateRegistry.createRegistry(PORT);
            //registry.rebind(JNDI_NAME_Conexion, localRemotoImpl);
            registry.rebind(JNDI_NAME_Conexion, localConexionImpl);
            diplay(TDSLanguageUtils.getMessage("Server.ConexionOK"));
            registry.rebind(JNDI_NAME_Reparaciones, localReparacionesImpl);
            diplay(TDSLanguageUtils.getMessage("Server.ReparacionesOK"));
            registry.rebind(JNDI_NAME_Administrativa, localAdministrativaImpl);
            diplay(TDSLanguageUtils.getMessage("Server.AdministrativaOK"));
            registry.rebind(JNDI_NAME_Estadisticas, localRemotoImpl);
            diplay(TDSLanguageUtils.getMessage("Server.EstadisticaOK"));
            activo=true;
            setServidorActivo(activo);            
        } catch (RemoteException localRemoteException) {
            this.jLabel2.setText(TDSLanguageUtils.getMessage("Server.RMIKO"));
            Utils.shownError(TDSLanguageUtils.getMessage("Server.RMIKO"), TDSLanguageUtils.getMessage("Server.RMIKOTitle"));
        } catch (ExceptionBD bdException) {
            Utils.shownError(bdException.getMessage(), TDSLanguageUtils.getMessage("Server.RMIKOTitle"));
        } catch (Exception localException) {
            this.jLabel2.setText(TDSLanguageUtils.getMessage("Aplication.ExcpGeneral"));
            Utils.shownError(TDSLanguageUtils.getMessage("Aplication.ExcpGeneral"), TDSLanguageUtils.getMessage("Server.RMIKOTitle"));
        }
    }
    
    public void StopRMIServidor() {
        try {
            if (activo==true) {
                registry.unbind(JNDI_NAME_Conexion);
                diplay(TDSLanguageUtils.getMessage("Server.ConexionKO"));
                registry.unbind(JNDI_NAME_Reparaciones);
                diplay(TDSLanguageUtils.getMessage("Server.MantenimientoKO"));
                registry.unbind(JNDI_NAME_Administrativa);
                diplay(TDSLanguageUtils.getMessage("Server.AdministrativaKO"));
                registry.unbind(JNDI_NAME_Estadisticas);
                diplay(TDSLanguageUtils.getMessage("Server.EstadisticaKO"));
                try {
                    UnicastRemoteObject.unexportObject(registry,false);
                } catch (NoSuchObjectException unicastRemoteException) {
                    this.jLabel2.setText(TDSLanguageUtils.getMessage("Server.RMIKO"));
                    Utils.shownError(TDSLanguageUtils.getMessage("Server.RMIKO"), TDSLanguageUtils.getMessage("Server.RMIKOTitle"));
                    diplay(TDSLanguageUtils.getMessage("Server.RMIKO"));
                }
                activo=false;
                setServidorActivo(activo);
                
            }
        } catch (RemoteException localRemoteException) {
            this.jLabel2.setText(TDSLanguageUtils.getMessage("Server.RMIKO"));
            Utils.shownError(TDSLanguageUtils.getMessage("Server.RMIKO"), TDSLanguageUtils.getMessage("Server.RMIKOTitle"));
        } catch (Exception localException) {
            Utils.shownError(TDSLanguageUtils.getMessage("Server.RMIDesKO"));
        }
    }
    
    private void setServidorActivo(boolean paramBoolean) {
        this.jButton1.setEnabled(!paramBoolean);
        this.jButton2.setEnabled(paramBoolean);
        if (paramBoolean) {
            this.jLabel2.setText(TDSLanguageUtils.getMessage("Server.InitOK"));
            diplay(TDSLanguageUtils.getMessage("Server.InitOK"));
        } else {
            this.jLabel2.setText(TDSLanguageUtils.getMessage("Server.Pendiente"));
            diplay(TDSLanguageUtils.getMessage("Server.Pendiente"));
        }
    }
    
    public static void diplay(String texto){
        text.append("[Fecha: " + getDateTime() + "]" + texto + " " +"\n");
    }

    private static String getDateTime() {
        DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
        Date date = new Date();
        return dateFormat.format(date);
    }
}
